<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.materialCode" placeholder="物料编码" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQuery" />
      <el-input v-model="listQuery.materialName" placeholder="物料名称" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQuery" />
      <el-input v-model="listQuery.materialSpecification" placeholder="物料规格" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQuery" />
      <el-input v-model="listQuery.materialType" placeholder="类型" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQuery" />
      <el-dropdown split-button type="primary" class="filter-item" @click="btnQuery">
        <i class="el-icon-search el-icon--left" />查询
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-zoom-out" @click.native="btnReset">重置</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button-group>
        <el-button v-permission="'purchase:material:save'" icon="el-icon-plus" type="primary" class="filter-item" @click="btnCreate">新增</el-button>
        <el-button v-permission="'purchase:material:delete'" icon="el-icon-delete" class="filter-item" @click="btnDelete()">批量删除</el-button>
      </el-button-group>
    </div>
    <el-table
      ref="multipleTable"
      :data="records"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :cell-style="{padding:'3px'}"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="物料编码" prop="materialCode" align="center" width="100px"><template slot-scope="scope"><span>{{ scope.row.materialCode }}</span></template></el-table-column>
      <el-table-column label="物料名称" prop="materialName" align="center"><template slot-scope="scope"><span>{{ scope.row.materialName }}</span></template></el-table-column>
      <el-table-column label="物料规格" prop="materialSpecification" align="center"><template slot-scope="scope"><span>{{ scope.row.materialSpecification }}</span></template></el-table-column>
      <el-table-column label="单价（元）" prop="unitPrice" align="center" width="70px"><template slot-scope="scope"><span>{{ scope.row.unitPrice }}</span></template></el-table-column>
      <el-table-column label="单位" prop="unit" align="center" width="50px"><template slot-scope="scope"><span>{{ scope.row.unit }}</span></template></el-table-column>
      <el-table-column label="版本号" prop="materialVersion" align="center" width="50px"><template slot-scope="scope"><span>{{ scope.row.materialVersion }}</span></template></el-table-column>
      <el-table-column label="备注" prop="comment" align="center"><template slot-scope="scope"><span>{{ scope.row.comment }}</span></template></el-table-column>
      <el-table-column label="类型" prop="materialType" align="center" width="70px"><template slot-scope="scope"><span>{{ scope.row.materialType }}</span></template></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button-group style="float: left;">
            <el-button type="text" @click.native="btnView(row)">查看</el-button>
            <el-button v-permission="'purchase:material:delete'" style="margin-left: 5px" type="text" divided @click.native="btnDelete(row.id)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :current.sync="listQuery.current"
      :size.sync="listQuery.size"
      @pagination="list"
    />

    <el-dialog title="" :visible.sync="dialogFormVisible" width="80%">
      <el-form ref="dataForm" :rules="rules" :model="temp" :disabled="dialogStatus==='view'" label-position="right" label-width="110px">
        <el-col :span="12"><el-form-item v-show="false" label="ID" prop="id"><el-input v-model="temp.id" :readonly="dialogStatus==='update'" /></el-form-item></el-col>
        <el-col :span="12"><el-form-item label="物料编码" prop="materialCode"><el-input v-model="temp.materialCode" /></el-form-item></el-col>
        <el-col :span="12"> <el-form-item label="物料名称" prop="materialName"><el-input v-model="temp.materialName" /></el-form-item></el-col>
        <el-col :span="12"><el-form-item label="物料规格" prop="materialSpecification"><el-input v-model="temp.materialSpecification" /></el-form-item></el-col>
        <el-col :span="12"><el-form-item label="单价（元）" prop="unitPrice"><el-input v-model="temp.unitPrice" /></el-form-item></el-col>
        <el-col :span="12"><el-form-item label="单位" prop="unit"><el-input v-model="temp.unit" /></el-form-item></el-col>
        <el-col :span="12"><el-form-item label="类型" prop="materialType"><el-input v-model="temp.materialType" /></el-form-item></el-col>
        <el-form-item label="备注" prop="comment"><el-input v-model="temp.comment" /></el-form-item>
      </el-form>
      <div v-if="dialogStatus == 'view'" class="filter-container">
        <el-date-picker v-model="listOrderQuery.startDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="审批单开始日期" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQueryOrderDetail" />
        <el-date-picker v-model="listOrderQuery.endDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="审批单结束日期" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQueryOrderDetail" />
        <el-button split-button type="primary" class="filter-item" @click="btnQueryOrderDetail">
          <i class="el-icon-search el-icon--left" />查询
        </el-button>
      </div>
      <el-table
        v-if="dialogStatus == 'view'"
        ref="detailTable"
        show-summary
        :summary-method="getSummaries"
        :data="orderDetail"
        border
        style="width: 100%"
      >
        <el-table-column label="序号" type="index" />
        <el-table-column prop="orderCode" label="审批单编号" align="center" width="100px" />
        <el-table-column prop="orderDate" label="审批单日期" align="center" width="100px" />
        <el-table-column prop="materialNum" label="采购数量" align="center" width="50px" />
        <el-table-column prop="materialTotalPrice" label="总价（元）" align="center" width="100px" />
        <el-table-column prop="projectName" label="项目（用途）" align="center" />
        <el-table-column prop="contractCode" label="合同编号" align="center" width="150px" />
        <el-table-column prop="supplierName" label="供应商" align="center" width="200px" />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus!=='view'" icon="el-icon-check" type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="confirmDialogVisible"
      width="30%"
    >
      <span>确定删除</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doDelete()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { getAction, putAction, postAction, deleteAction } from '@/api/manage'
import { Message } from 'element-ui'

export default {
  name: 'PurchaseMaterial',
  components: { Pagination },
  data() {
    return {
      deleteIds: [],
      dicts: [],
      records: null,
      selectedRecords: [],
      total: 0,
      listQuery: {
        current: 1,
        size: 10,
        materialCode: undefined,
        materialName: undefined,
        materialSpecification: undefined,
        materialType: undefined
      },
      listOrderQuery: {
        materialId: undefined,
        startDate: undefined,
        endDate: undefined
      },
      confirmDialogVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      temp: {
        id: undefined,
        materialCode: '',
        materialName: '',
        materialSpecification: '',
        unitPrice: '',
        unit: '',
        materialVersion: '',
        comment: '',
        materialType: ''
      },
      orderDetail: null,
      rules: {
        // id: [{required: true, message: '该项不能为空', trigger: 'change'}],
        materialName: [{ required: true, message: '该项不能为空', trigger: 'change' }]
      }
    }
  },
  beforeCreate() {

  },
  created() {
    this.list()
  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param
      if (data === null || data === undefined) {
        return
      }
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column === undefined || (column.property !== 'materialTotalPrice' && column.property !== 'materialNum')) {
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        }
      })

      return sums
    },
    list() {
      getAction('/purchase/material/list', this.listQuery).then(res => {
        const { data } = res
        this.records = data.records
        this.total = data.total
      })
    },
    listOrder() {
      this.listOrderQuery.materialId = this.temp.id
      getAction('/purchase/orderDetail/listBy', this.listOrderQuery).then(res => {
        const { data } = res
        this.orderDetail = data
        this.$nextTick(() => {
          this.orderDetail = data
          // this.$refs['detailTable'].setData(data)
        })
      })
    },
    btnQuery() {
      this.listQuery.current = 1
      this.list()
    },
    btnQueryOrderDetail() {
      this.listOrder()
    },
    btnReset() {
      this.listQuery = {
        current: 1,
        size: 10,
        materialName: undefined,
        materialSpecification: undefined,
        materialType: undefined
      }
      this.list()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        materialName: '',
        materialSpecification: '',
        unitPrice: '',
        unit: '',
        comment: '',
        materialType: ''
      }
    },
    btnView(row) {
      this.temp = Object.assign({}, row)
      // 查询detail
      var param = { 'materialId': row.id }
      getAction('/purchase/orderDetail/listBy', param).then(res => {
        const {
          data
        } = res
        this.orderDetail = data
        this.dialogStatus = 'view'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    btnCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      // todo
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          postAction('/purchase/material/save', this.temp).then(({ msg }) => {
            this.dialogFormVisible = false
            Message.success(msg)
            this.list()
          })
        }
      })
    },
    btnUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      // todo
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          putAction('/purchase/material/update', this.temp).then(({ msg }) => {
            this.dialogFormVisible = false
            Message.success(msg)
            this.list()
          })
        }
      })
    },
    doDelete() {
      deleteAction('/purchase/material/delete', {
        ids: this.deleteIds.toString()
      }).then(({ msg }) => {
        Message.success(msg)
        this.list()
      })
      this.confirmDialogVisible = false
    },
    btnDelete(id) {
      const ids = id ? [id] : this.selectedRecords.map(record => {
        return record.id
      })
      if (ids.length === 0) {
        Message.error('请选择要删除的记录')
        return
      }
      this.deleteIds = ids
      this.confirmDialogVisible = true
    },
    selectionChange(selectedRecords) {
      this.selectedRecords = selectedRecords
    }
  }
}
</script>
